//  <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
//
//          EXIF ReName
//          Copyright (C) 2007 - 2021 Ingemar Ceicer
//          https://gitlab.com/posktomten/exifrename2
//          ic_0002 (at) ceicer (dot) com
//
//   This program is free software: you can redistribute it and/or modify
//   it under the terms of the GNU General Public License version 3
//   as published by the Free Software Foundation.
//
//   This program is distributed in the hope that it will be useful,
//   but WITHOUT ANY WARRANTY; without even the implied warranty of
//   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//   GNU General Public License for more details.
//
// <(((*> <(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*> ><(((*>
#include "mainwindow.h"
#include "exif.h"
#include "tabwidget.h"
#include "ui_mainwindow.h"
#include "selectfont.h"
#include "ui_selectfont.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent), ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->setWindowTitle(DISPLAY_NAME " " VERSION);
    this->setAcceptDrops(true);
    firstRun();
    readPlaceonscreen();
    connectLanguage();
    zoom();
    QPalette p = ui->textBrowserMain->palette(); // define pallete for textEdit..
    p.setColor(QPalette::Base, QColor(RED, GREEN, BLUE)); // set color "Red" for textedit base
//    p.setColor(QPalette::Text, QColor(0, 0, 0)); // set text color which is selected from color pallete
    ui->textBrowserMain->setPalette(p); // change textedit palette
    connect(this, &MainWindow::filKlar, ui->progressBar, &QProgressBar::setValue);
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Tooltips");
    bool showtooltips = settings.value("showtooltips", true).toBool();
    settings.endGroup();
    settings.beginGroup("Tools");

    if(showtooltips) {
        ui->menubar->setToolTipDuration(10000);
        ui->menuFile->setToolTipsVisible(true);
    } else {
        ui->menuFile->setToolTipsVisible(false);
    }

    if(settings.value("checkonstart", true).toBool()) {
        checkOnStart();
    }

    settings.endGroup();
    settings.beginGroup("Path");
//    QString path = settings.value("copypath").toString();
    settings.endGroup();
    // iapc
    //TabWidget::pathExist(path);// Kollar om alwayscopyto funkar
    /* SLUT toolBar */
    /* FILE*/
    connect(ui->actionClose, &QAction::triggered, [&]() -> void { close(); });
    connect(ui->actionRename, &QAction::triggered, this, &MainWindow::openFile);
    connect(ui->actionRenameRecursively, &QAction::triggered, this, &MainWindow::openFileRecursively);
    connect(ui->actionCopy, &QAction::triggered, this, &MainWindow::openCopy);
    connect(ui->actionClear, &QAction::triggered, ui->textBrowserMain, &QTextEdit::clear);
    connect(ui->actionClear, &QAction::triggered, [ & ](int value = 0) {
        ui->progressBar->setValue(value);
    });
    /* SHORTCUT */
    ui->actionIn->setShortcut(QKeySequence(tr("Ctrl++")));
    ui->actionOut->setShortcut(QKeySequence(tr("Ctrl+-")));
    ui->actionDefault->setShortcut(QKeySequence(tr("Ctrl+0")));
    /* EDIT */
    /* CHANGE EXIF */
    connect(ui->actionChangeEXIF, &QAction::triggered, [this]() {
        changeExif(false);
    });
    /* CHANGE EXIF AND RENAME */
    connect(ui->actionChangeEXIFRename, &QAction::triggered, [this]() {
        changeExif(true);
    });
    /* CHANGE EXIF OFFSET */
    connect(ui->actionEditEXIFOffset, &QAction::triggered, [this]() {
        changeExifOffset();
    });
    /* CHANGE EXIF OFFSET RENAME */
    connect(ui->actionEditEXIFOffsetRename, &QAction::triggered, [this]() {
        changeExifOffsetManyfilesRename();
    });
    /* END EDIT */
    /* TOOLS */
    /* TAB WIDGET File Name Pattern */
    connect(ui->actionSettings, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(0);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);




#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* FONT */
    connect(ui->actionFont, &QAction::triggered, [this]() {
        SelectFont *sf = new SelectFont;
        sf->show();
        connect(sf, &SelectFont::valueChanged, this, &MainWindow::getFont);
        ui->actionFont->setDisabled(true);
        connect(sf, &SelectFont::selectFontClose, this, &MainWindow::selectFontClose);
    });
    /* END FONT */
    /* Extensions */
    connect(ui->actionExtensions, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(1);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);
#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* Open / Copy to */
    connect(ui->actionOpenCopy, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(2);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);
#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* Miscellaneous */
    connect(ui->actionMiscellaneous, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(3);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);
#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* Update */
    connect(ui->actionUpdate, &QAction::triggered, [this]() -> void {
#ifdef Q_OS_LINUX
        // QDialog class
        UpdateDialog *ud = new UpdateDialog;
        ud->show();
        // QObject class
        Update *up = new Update;
        // Contact is established, the slot "isUpdated" listens for a signal from
        // the update class "isUpdated"
        connect(up, &Update::isUpdated, this, &MainWindow::isUpdated);

        // Pointer is sent so that "ud" can be deleted
        up->doUpdate(ARG1, ARG2, DISPLAY_NAME, ud);
#endif
#ifdef Q_OS_WIN // Windows 32- and 64-bit
        QString path =
        QDir::toNativeSeparators(QCoreApplication::applicationDirPath() +
                                 "/exifrenameMaintenanceTool.exe");

        bool b = QProcess::startDetached(path, QStringList() << "");

        if(!b)
            QMessageBox::critical(
                this, DISPLAY_NAME " " VERSION,
                tr("Maintenance Tool cannot be found.\nOnly if you install ") +
                DISPLAY_NAME +
                tr(" is it possible to update and uninstall the program."));
#endif
    });
    /* Delete all settings */
    connect(ui->actionDeleteAllSettings, &QAction::triggered, [this]() {
        QMessageBox msgDeleteAllSettings(QMessageBox::Warning, DISPLAY_NAME " " VERSION, tr("Do you want to delete all saved settings and shortcuts?\nThey cannot be restored.") + "\n" DISPLAY_NAME " " VERSION  + " " + tr("closes."), QMessageBox::Yes | QMessageBox::No, this);
        msgDeleteAllSettings.setDefaultButton(QMessageBox::No);
        msgDeleteAllSettings.setButtonText(QMessageBox::Yes, tr("Yes"));
        msgDeleteAllSettings.setButtonText(QMessageBox::No, tr("No"));
        int ret = msgDeleteAllSettings.exec();

        if(ret == QMessageBox::No) {
            return;
        }

        QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                           EXECUTABLE_NAME);
        QString inifile = settings.fileName();
        QFileInfo fi(inifile);
        QString f = fi.absolutePath();
        QDir dir(f);
        dir.removeRecursively();
        const QString shortcutlocationdesktop = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::DesktopLocation));
        const QString shortcutlocationapplications = QDir::toNativeSeparators(QStandardPaths::writableLocation(QStandardPaths::ApplicationsLocation));
// Desktop
#ifdef Q_OS_WIN
        QString link(QDir::toNativeSeparators(shortcutlocationdesktop + "/EXIF ReName.lnk"));
#endif
#ifdef Q_OS_LINUX
        QString link(QDir::toNativeSeparators(shortcutlocationdesktop + "/exifrename.desktop"));
#endif
        QFile file(link);

        if(file.exists()) {
            if(!file.remove()) {
                QMessageBox::critical(this, DISPLAY_NAME " " VERSION,
                                      tr("Failed to delete your configuration files. "
                                         "Check your file permissions."));
            }
        }

// ApplicationsLocation
#ifdef Q_OS_WIN
        link = QDir::toNativeSeparators(shortcutlocationapplications + "/EXIF ReName.lnk");
#endif
#ifdef Q_OS_LINUX
        link = QDir::toNativeSeparators(shortcutlocationapplications + "/exifrename.desktop");
#endif
        file.setFileName(link);

        if(file.exists()) {
            file.remove();
        }

        close();
    });
    /* END Delete all settings */
    /* END TOOLS */
    /* HELP */
    /* TAB WIDGET License */
    connect(ui->actionLicense, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(4);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);
#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* TAB WIDGET About */
    connect(ui->actionAbout, &QAction::triggered, [this]() -> void {
        this->setDisabled(true);

        TabWidget *tabwidget = new TabWidget(nullptr);
        tabwidget->setCurrentIndex(5);
        tabwidget->show();
        connect(tabwidget, &TabWidget::tabwidgetclosing, this,
                &MainWindow::getCloseSignalTabWidget);
#ifdef Q_OS_LINUX
        connect(tabwidget, &TabWidget::mainwindowclosing, this,
                &MainWindow::timeToClose);
#endif
    });
    /* Check for updates */
    connect(ui->actionCheckForUpdates, &QAction::triggered,
            [this]() -> void { doCheckForUpdates(); });
}
void MainWindow::dragEnterEvent(QDragEnterEvent *ev)
{
    ev->accept();
}
void MainWindow::dropEvent(QDropEvent *ev)
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Tools");
    QString draganddrop = settings.value("draganddrop").toString();
    settings.endGroup();

    if(draganddrop == "rename") {
        QList<QUrl> urls = ev->mimeData()->urls();
        findExif(urls);
    } else if(draganddrop == "copy")  {
        QList<QUrl> urls = ev->mimeData()->urls();
        copy(urls);
    }
}



// public slots:
void MainWindow::getCloseSignalTabWidget()
{
    // Then tabwidger close
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    settings.setIniCodec("UTF-8");
    settings.beginGroup("Toolbar");
    bool close = settings.value("close", true).toBool();
    bool clear = settings.value("clear", true).toBool();
    bool copyrename = settings.value("copyrename", true).toBool();
    bool editexif = settings.value("editexif", false).toBool();
    bool editexifoffset = settings.value("editexifoffset", false).toBool();
    bool editexifoffsetrename = settings.value("editexifoffsetrename", false).toBool();
    bool editexifrename = settings.value("editexifrename", false).toBool();
    bool rename = settings.value("rename", true).toBool();
    bool renamerecursively = settings.value("renamerecursively", false).toBool();
    settings.endGroup();

    /* toolBAr */
    if(close) {
        ui->toolBar->addAction(ui->actionClose);
    } else {
        ui->toolBar->removeAction(ui->actionClose);
    }

    if(rename) {
        ui->toolBar->addAction(ui->actionRename);
    } else {
        ui->toolBar->removeAction(ui->actionRename);
    }

    if(renamerecursively) {
        ui->toolBar->addAction(ui->actionRenameRecursively);
    } else {
        ui->toolBar->removeAction(ui->actionRenameRecursively);
    }

    if(copyrename) {
        ui->toolBar->addAction(ui->actionCopy);
    } else {
        ui->toolBar->removeAction(ui->actionCopy);
    }

    if(clear) {
        ui->toolBar->addAction(ui->actionClear);
    } else {
        ui->toolBar->removeAction(ui->actionClear);
    }

    if(editexif) {
        ui->toolBar->addAction(ui->actionChangeEXIF);
    } else {
        ui->toolBar->removeAction(ui->actionChangeEXIF);
    }

    if(editexifoffset) {
        ui->toolBar->addAction(ui->actionEditEXIFOffset);
    } else {
        ui->toolBar->removeAction(ui->actionEditEXIFOffset);
    }

    if(editexifrename) {
        ui->toolBar->addAction(ui->actionChangeEXIFRename);
    } else {
        ui->toolBar->removeAction(ui->actionChangeEXIFRename);
    }

    if(editexifoffsetrename) {
        ui->toolBar->addAction(ui->actionEditEXIFOffsetRename);
    } else {
        ui->toolBar->removeAction(ui->actionEditEXIFOffsetRename);
    }

    settings.beginGroup("Tooltips");
    bool showtooltips = settings.value("showtooltips", true).toBool();
    settings.endGroup();
    settings.beginGroup("Tools");

    if(showtooltips) {
        ui->menubar->setToolTipDuration(10000);
        ui->menuFile->setToolTipsVisible(true);
    } else {
        ui->menuFile->setToolTipsVisible(false);
    }

    this->setEnabled(true);
}
void MainWindow::setEndConfig()
{
    QSettings settings(QSettings::IniFormat, QSettings::UserScope, DISPLAY_NAME,
                       EXECUTABLE_NAME);
    QString inifile = settings.fileName();
    QFileInfo fi(inifile);

    if(fi.exists()) {
        writePlaceonscreen();
    }
}
MainWindow::~MainWindow()
{
    writePlaceonscreen();
    setEndConfig();
    delete ui;
}
// private slotts:
void MainWindow::isUpdated(bool b)
{
    if(b) {
        close();
    } else {
        QMessageBox::critical(this, DISPLAY_NAME " " VERSION,
                              tr("An unexpected error occurred while updating."));
    }
}
#ifdef Q_OS_LINUX
// private slotts:
void MainWindow::timeToClose()
{
    close();
}
#endif
